public class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }

        int[][] ans = new int[r][c];
        for (int x = 0; x < m * n; ++x) {
            ans[x / c][x % c] = nums[x / n][x % n];
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        int[][] nums = {
                {1, 2, 3, 4}
        };
        int r = 2;
        int c = 2;
        int[][] reshaped = solution.matrixReshape(nums, r, c);
        for (int i = 0; i < reshaped.length; i++) {
            for (int j = 0; j < reshaped[0].length; j++) {
                System.out.print(reshaped[i][j] + " ");
            }
            System.out.println();
        }
    }
}